package com.example.thirdhomework

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

const val FIRST_MSG = "FIRST_MSG"
const val SECOND_MSG = "SECOND_MSG"
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()// 启用边缘到边缘的显示
        setContentView(R.layout.activity_main)// 设置布局文件
        // 设置窗口插入监听器，以调整视图的填充
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
             val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
             v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
             insets
         }

        val first: Button = findViewById(R.id.first)// 获取按钮视图
        val second: Button = findViewById(R.id.second) // 获取第二个按钮视图
        val third: Button = findViewById(R.id.third) // 获取第三个按钮视图
        val fourth: Button = findViewById(R.id.fourth) // 获取第四个按钮视图
        val editText: EditText = findViewById(R.id.editText) // 获取编辑文本视图


        // 设置按钮点击监听器
        first.setOnClickListener {
            val intent = Intent(this, SecondActivity::class.java)// 创建意图，启动 SecondActivity
            intent.putExtra(FIRST_MSG, editText.text.toString())// 将编辑文本的内容作为额外信息传递
            startActivity(intent)// 启动 SecondActivity
        }
        // 设置第二个按钮点击监听器
        second.setOnClickListener {
            val intent = Intent(this, ThirdActivity::class.java)// 创建意图，启动 ThirdActivity
            startActivityForResult(intent, requestCode = 1)// 启动 ThirdActivity 并请求结果

        }

        third.setOnClickListener {
            val intent = Intent(this, FourthActivity::class.java)
            startActivity(intent) // 启动 ThirdActivity
        }

        fourth.setOnClickListener {
            val intent = Intent(this, FifthActivity::class.java)
            startActivity(intent) // 启动 FifthActivity
        }
    }
    // 重写 onActivityResult 方法以处理返回的结果
    override  fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data) // 调用父类的 onActivityResult 方法
        val textView : TextView= findViewById(R.id.textView) // 获取 TextView 视图
        if (requestCode == 1) {// 检查请求码是否为 1
            if (resultCode == 2) { // 检查结果码是否为 2
                textView.text = data?.getStringExtra(SECOND_MSG)// 设置 TextView 的文本为返回的额外信息以及判空
            }
         }
     }
}